<template>
  <div class="order-detail-box">
    <div class="order-info-box">
      <div class="order-info">
        <div class="title">订单信息</div>
        <div class="info-item" v-for="(item, index) in orderInfo" :key="index">
          <div class="label">{{ item.label }} :</div>
          <div class="value">{{ item.value }}</div>
        </div>
        <div class="info-item" v-if="detail.status == '-1'">
          <div class="label">驳回理由 :</div>
          <div class="value">{{ detail.bohui_context }}</div>
        </div>
        <div class="info-item">
          <div class="label">后台备注 :</div>
          <div class="value" style="flex-grow: 1">
            <el-input @click.stop="" v-model="detail.houtaibeizhu" :rows="3" type="textarea" placeholder="后台备注" />
            <el-button type="primary" @click.stop="beizhuChange(order_sn, detail.houtaibeizhu)" size="small"
              class="el-button" style="margin-top: 10px; margin-bottom: 10px">
              确认编辑
            </el-button>
          </div>
        </div>
      </div>
      <div class="order-status">
        <div class="btn-box">
          <el-button type="danger" size="small" @click="cancelOrder" round>取消订单 </el-button>
        </div>
        <el-steps :active="stepAct" finish-status="success" align-center>
          <el-step :title="item.label" style="cursor: pointer" v-for="(item, index) in steps" :key="index"
            @click="stepCli(item, index)" />
        </el-steps>
      </div>
    </div>
    <div class="address-box">
      <div class="take-address">
        <div class="title">下单人地址</div>
        <div class="address-item" v-for="(item, index) in orderAddress" :key="index">
          <div class="label">{{ item.label }} :</div>
          <div class="value">{{ item.value }}</div>
        </div>
      </div>
      <div class="send-address">
        <div class="title">配送信息</div>
        <div class="address-item" v-for="(item, index) in orderWuLiu" :key="index">
          <div class="label">{{ item.label }} :</div>
          <div class="value">{{ item.value }}</div>
        </div>
      </div>
      <div class="wuliu">
        <div class="title">物流信息</div>
        <div class="wuliu-item" v-for="(item, index) in wuliu" :key="index">
          <div class="time">{{ item.time }}</div>
          <div class="status">{{ item.site }}</div>
          <div class="status">{{ item.description }}</div>
        </div>
      </div>
    </div>

    <el-table :data="detail.list" border style="width: 100%">
      <el-table-column prop="id" label="编号" align="center" width="80px" header-align="center"></el-table-column>

      <el-table-column prop="images" label="封面" align="center" header-align="center">
        <template #default="scope">
          <img style="width: 100px; height: 120px" v-if="scope.row.images" :src="scope.row.images" alt="" />
        </template>
      </el-table-column>

      <el-table-column prop="name" label="书籍名称" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="isbn" label="isbn编码" align="center" header-align="center">
        <template #default="scope">
          <div>{{ scope.row.isbn }}</div>
          <el-button type="primary" style="font-size: 12px; padding: 0 8px" @click="bijiaFun(scope.row.isbn)"
            class="el-button">
            <span>淘宝比价</span>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column prop="weihurenname" label="维护人" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="weihutime" label="维护时间" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="number" label="数量" align="center" header-align="center">
        <template #default="scope">
          <el-input v-if="detail.status == '4'" v-model="scope.row.number" placeholder=""
            @change="changeNumber(scope.row)" />
          <div v-else>{{ scope.row.number }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="price" label="单价" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="sum" label="总价" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="status" label="状态" align="center" header-align="center">
        <template #default="scope">
          <div :style="scope.row.statusStyle">{{ scope.row.statusText }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="shuji_images" label="不通过理由图片" align="center" header-align="center">
        <template #default="scope">
          <img style="width: 100px; height: 120px" v-if="scope.row.shuji_images" :src="scope.row.shuji_images" alt="" />
        </template>
      </el-table-column>

      <el-table-column prop="context" label="不通过理由备注" align="center" header-align="center"> </el-table-column>

      <el-table-column label="操作" align="center" header-align="center" width="160px">
        <template #default="scope">
          <el-button type="primary" @click="shenheFun(scope.row.id, scope.row.number)"
            v-if="detail.status == '3' && scope.row.status == '0'">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="sum-box">
      <div class="label">总金额:</div>
      <div class="sum">￥{{ detail.price }}</div>
    </div>
  </div>

  <el-dialog v-model="showQujian" title="取件物流信息">
    <el-form ref="qujianFormRef" :model="qujianForm" :rules="qujianRules" label-width="126px">
      <el-form-item label="物流公司名称:" prop="wuliu_name">
        <el-input v-model="qujianForm.wuliu_name" clearable />
      </el-form-item>
      <el-form-item label="物流编号:" prop="wuliu_sn">
        <el-input v-model="qujianForm.wuliu_sn" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showQujian = false">取消</el-button>
        <el-button type="primary" @click="qujianConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 审核 -->
  <addEdit :show="showShenHe" :id="shenHeId" :count="shenheCount" @hide-addEdit="hideShenHe" />
</template>
<script setup>
import { onMounted, ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getOrderDetile, updateOderQujian, updateOderStatus, UpdateOrderHoutaibei, getWuliuMessage, ChaxunJD, updateOrderItemNubmer } from '@api/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import addEdit from './components/addEdit.vue'

const router = useRouter()
const route = useRoute()
const detail = ref({})
const order_sn = ref('')
const orderAddress = ref([])
const orderInfo = ref([])
const orderWuLiu = ref([])

const qujianRules = reactive({
  wuliu_sn: [{ required: true, message: '物流编号不能为空!', trigger: 'blur' }],
  wuliu_name: [{ required: true, message: '物流公司名称不能为空!', trigger: 'blur' }]
})

const statusArr = ['正常', '不通过']
const statusStyles = ['color: #67c23a', 'color: #f44236']
const getDetail = async () => {
  let res = await getOrderDetile({ order_sn: order_sn.value })
  if (res.code) {
    detail.value = {
      ...res.data,
      list: res.data.list.map((v) => {
        return {
          ...v,
          sum: parseFloat(v.number * v.price).toFixed(2),
          statusText: statusArr[parseInt(v.status)],
          statusStyle: statusStyles[parseInt(v.status)]
        }
      }),
      bohui_context: res.data.bohui_context ? JSON.parse(res.data.bohui_context).value : ''
    }
    const { order_sn, status, createtime, username, consignee, province, city, county, streent, tel, wuliu_name, wuliu_sn, wuliutype, postcode, qujianren } = res.data
    orderAddress.value = [
      {
        label: '下单人',
        value: username
      },
      {
        label: '联系人',
        value: consignee
      },
      {
        label: '省市区',
        value: `${province}/${city}/${county}`
      },
      {
        label: '街道',
        value: streent
      },
      {
        label: '详细地址',
        value: postcode
      },
      {
        label: '电话',
        value: tel
      }
    ]

    orderInfo.value = [
      {
        label: '订单编号',
        value: order_sn
      },
      {
        label: '创建时间',
        value: createtime
      }
    ]

    // getWuLiu(wuliu_sn, wuliutype)
    if (wuliu_name && wuliu_sn) {
      orderWuLiu.value = [
        {
          label: '物流公司',
          value: wuliu_name
        },
        {
          label: '物流单号',
          value: wuliu_sn
        },
        {
          label: '取件人',
          value: qujianren
        }
      ]

      getWuLiu(wuliu_sn, wuliutype)
    } else {
      orderWuLiu.value = []
    }

    // 重置状态
    steps.value = [
      {
        label: '待审核',
        value: '0'
      },
      {
        label: '待取件',
        value: '1'
      },
      {
        label: '待收货',
        value: '2'
      },
      {
        label: '待验货',
        value: '3'
      },
      {
        label: '待打款',
        value: '4'
      }
    ]

    if (status == '-1') {
      steps.value.unshift({
        label: '已取消',
        value: '-1'
      })
    } else {
      if (parseInt(status) > 0) {
        steps.value.forEach((v, i, arr) => {
          if (i < parseInt(status)) {
            steps.value[i].label = steps.value[i].label.replace('待', '已')
          }
        })
      }
    }
    setStepAct(status)
  }
}

// 获取物流信息
const wuliu = ref([])
const getWuLiu = async (wuliu_sn, wuliutype) => {
  if (wuliutype == '0') {
    let res = await getWuliuMessage({ wuliu: wuliu_sn })
    if (res.code == 200) {
      wuliu.value = res.data
    }
  } else if (wuliutype == '1') {
    let res = await ChaxunJD({ wuliusn: wuliu_sn })
    if (res.code == 200) {
      wuliu.value = res.data.map(v => {
        return {
          time: v.operationTime,
          site: v.operationTitle,
          description: v.operationRemark
        }
      })
    }
  }

}

const stepAct = ref(1)
const steps = ref([
  {
    label: '待审核',
    value: '0'
  },
  {
    label: '待取件',
    value: '1'
  },
  {
    label: '待收货',
    value: '2'
  },
  {
    label: '待验货',
    value: '3'
  },
  {
    label: '待打款',
    value: '4'
  }
])

const setStepAct = (value) => {
  if (value == -1) {
    value = 1
  }
  stepAct.value = value
}

// 步骤
const stepCli = async (item, index) => {
  let res = ''
  const status = detail.value.status + ''
  if (item.label.indexOf('已') >= 0) {
    return false
  }

  if (item.label == '待审核') {
    ElMessageBox.confirm('审核是否通过?', '审核提示', {
      distinguishCancelAndClose: true,
      confirmButtonText: '通过',
      cancelButtonText: '驳回',
      type: 'warning'
    })
      .then(async () => {
        res = await updateOderStatus({ order_sn: order_sn.value, status: parseInt(item.value) + 1 })
        if (res.code) {
          ElMessage({
            message: '操作成功!',
            type: 'success'
          })
          getDetail()
        }
      })
      .catch(async (Action, value) => {
        if (Action == 'cancel') {
          ElMessageBox.prompt('驳回理由?', '驳回提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async (value) => {
              res = await updateOderStatus({ order_sn: order_sn.value, status: '-1', bohuiliyou: value })
              if (res.code) {
                ElMessage({
                  message: '操作成功!',
                  type: 'success'
                })
                getDetail()
              }
            })
            .catch(async (Action, value) => { })
        }
      })

    return false
  }
  // if (item.value === '-1' || item.value === '0') {
  //   return false
  // }

  // if (item.value === '-1') {
  //   if (status == '0') {
  //     res = await updateOderStatus({ order_sn: order_sn.value, status: item.value })
  //   }
  // } else if (item.value === '2' || item.value === '3') {
  //   if (parseInt(status) >= 1) {
  //     res = await updateOderStatus({ order_sn: order_sn.value, status: item.value })
  //   }
  // } else if (item.value == '1' && status == '0') {
  //   showQujian.value = true
  // }
  let title = item.label.split('待')[1]
  ElMessageBox.confirm(`确定已${title}吗?`, '审核提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      res = await updateOderStatus({ order_sn: order_sn.value, status: parseInt(item.value) + 1 })

      if (res.code) {
        ElMessage({
          message: '操作成功!',
          type: 'success'
        })

        getDetail()
      }
    })
    .catch(() => { })
}

// 取消订单
const cancelOrder = () => {
  ElMessageBox.confirm(`确定取消订单吗?`, '审核提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await updateOderStatus({ order_sn: order_sn.value, status: -1 })

      if (res.code) {
        ElMessage({
          message: '操作成功!',
          type: 'success'
        })

        getDetail()
      }
    })
    .catch(() => { })
}

const qujianFormRef = ref()
const showQujian = ref(false)
const qujianForm = ref({
  wuliu_sn: '',
  wuliu_name: ''
})
const qujianConfirm = async () => {
  qujianFormRef.value.validate(async (valid) => {
    if (valid) {
      let res = await updateOderQujian({ order_sn: order_sn.value, wuliu_sn: qujianForm.value.wuliu_sn, wuliu_name: qujianForm.value.wuliu_name })

      if (res.code == 200) {
        ElMessage({
          message: '操作成功!',
          type: 'success'
        })
        showQujian.value = false
        getDetail()
      }
    }
  })
}

const showShenHe = ref(false)
const shenHeId = ref('')
const shenheCount = ref(0)
const hideShenHe = () => {
  getDetail()
  showShenHe.value = false
}
const shenheFun = (id, num) => {
  shenHeId.value = id
  showShenHe.value = true
  shenheCount.value = num
}

// 备注
const beizhuChange = async (ordersn, beizhu) => {
  let res = await UpdateOrderHoutaibei({ ordersn, beizhu })

  if (res.code) {
    ElMessage({
      message: '操作成功!',
      type: 'success'
    })

    getDetail()
  }
}

// 比价
const bijiaFun = (isbn) => {
  window.open(
    `https://s.taobao.com/search?q=${isbn}&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.jianhua.201856-taobao-item.2&ie=utf8&initiative_id=tbindexz_20170306&sort=sale-desc`
  )
}

// 改变数量
const changeNumber = async (row) => {
  let { number, id } = row

  let res = await updateOrderItemNubmer({ count: number, id })
  if (res.code == 200) {
    ElMessage({
      message: '操作成功!',
      type: 'success'
    })
    getDetail()
  }
}

onMounted(() => {
  order_sn.value = route.query.order_sn
  getDetail()
})
</script>
<style lang="scss">
.order-detail-box {
  .address-box {
    width: 100%;
    @include flex(row, flex-start, center);
    padding: 30px;
    padding-left: 0;
    box-sizing: border-box;
    border: 1px solid var(--borderColor);
    margin-bottom: 30px;

    .take-address {
      width: 500px;
      border-right: 1px solid var(--borderColor);
      padding: 0 20px;
      height: 190px;
      box-sizing: border-box;
    }

    .send-address {
      width: 500px;
      border-right: 1px solid var(--borderColor);
      padding: 0 20px;
      height: 190px;
      box-sizing: border-box;
    }

    .wuliu {
      flex-grow: 2;
      padding: 0 20px;
      height: 190px;
      overflow-y: auto;
      box-sizing: border-box;

      .wuliu-item {
        margin-bottom: 20px;

        .time {
          margin-bottom: 5px;
        }

        .status {
          font-weight: bold;
        }
      }
    }

    .title {
      color: #333;
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
    }

    .address-item {
      @include flex();
      margin-bottom: 10px;

      .label {
        width: 85px;
        color: #333;
        font-size: 14px;
      }

      .value {
        color: #333;
        font-size: 14px;
      }
    }
  }

  .order-info-box {
    width: 100%;
    @include flex(row, flex-start, center);
    padding: 30px;
    padding-left: 0;
    box-sizing: border-box;
    border: 1px solid var(--borderColor);
    margin-bottom: 30px;

    .order-info {
      width: 500px;
      border-right: 1px solid var(--borderColor);
      padding: 0 20px;
      box-sizing: border-box;

      .title {
        color: #333;
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 20px;
      }

      .info-item {
        @include flex(row, flex-start, flex-start);
        margin-bottom: 10px;

        .label {
          width: 85px;
          color: #333;
          font-size: 14px;
        }

        .value {
          color: #333;
          font-size: 14px;
        }
      }
    }

    .order-status {
      flex-grow: 2;
      position: relative;

      .btn-box {
        position: absolute;
        top: -65px;
        display: flex;
        justify-content: flex-end;
        width: 100%;
      }
    }
  }

  .sum-box {
    width: 100%;
    @include flex(row, flex-end, center);
    margin: 50px 0 30px 0;
    padding-right: 20px;
    box-sizing: border-box;

    .label {
      color: #666;
      margin-right: 80px;
    }

    .sum {
      color: var(--dangerColor);
      font-size: 20px;
      font-weight: bold;
    }
  }
}
</style>
